package com.eascs.banknet.boc.service.trans;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.jdom.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.dao.BOCB02Dao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.bocb02.BOCB02Element;
import com.eascs.banknet.boc.vo.bocb02.BOCB02Root;
import com.eascs.banknet.common.utils.XmlHelp;
import com.eascs.banknet.constant.EAContant;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.StringUtil;

@Service("bocB02Service")
public class BOCB02Service extends BOCAbstractService{
	private static final Logger logger = LoggerFactory.getLogger(BOCB02Service.class);
	
	@Autowired
	private BOCB02Dao bocB02Dao;
	
	private String startId = "";
	
	@Override
	public Map<String, String> dowork() {
		//不管成功or失败，都要记录当前执行startId，用于下一次轮询开始的标记，若没有扫描到数据则重置startId重新开始
		String loanapplyNo = "";
		String id = "";	
		LogEntity logEntity = initLogData();
		try {
			logger.info("授信信息调查开始......");
			/**
			 * 查询数据，组装请求xml
			 */
			//查询需要提交征信的贷款人信息
			BOCB02Root root = new BOCB02Root();
			List<BOCB02Element> dataList = bocB02Dao.queryData(startId);
			if(dataList.isEmpty()){
				startId = null;
				logger.info("授信信息调查,没有符合条件的数据");
				return null;
			}
			id = dataList.get(0).getAPPNO();
			loanapplyNo = loanapplyDao.getLoanapplyNoByAppno(id);
			startId = id;	
			//组装请求的xml消息
			List<BOCB02Element> elementList = new ArrayList<>();
			BOCB02Element object = dataList.get(0);
			for(BOCB02Element element : dataList){
				element.setCCTPERTRN_CBICERTY(EAContant.IDTypeMap.get(element.getCCTPERTRN_CBICERTY()));
				//中行测试环境只能用这个
				if("26.127.253.48".equals(bocUtil.getBocSocketInfo().getHref())){
					element.setCCTPERTRN_PERFSTNM("红丽");
					element.setCCTPERTRN_PERLSTNM("杨");
					element.setCCTPERTRN_CBICERNO("412926197205234920");
				}
				elementList.add(element);
			}
			root.getBody().setList(elementList);
			//保存xml文件到ftp服务器
			String xml = XmlHelp.convertToXml(root);
			XmlHelp.createXml("B02" + "(" + loanapplyNo + ")", loanapplyNo + "&" + xml, "BOCB02RQ", bocUtil.getEaFtpInfo());
			
			/*
			 * 调用中行接口
			 */
			logger.info("组装请求数据完成，开始调用中行B02接口, loanapplyNo:[{}], appno:{},xml:{}", loanapplyNo, id, xml);
			//加密XML信息
			String returnXml = bocNetService.executeSocket(bocUtil.getBocSocketInfo(), "B02", null, xml);
			if(StringUtil.isEmpty(returnXml)){
				logger.error("中行B02接口返回数据为空！");
				throw new Exception("中行B02接口返回数据为空");
			}
			logger.info("中行B02接口返回xml完成, returnXml：{}", returnXml);
			
			/*
			 * 解析返回xml，保存数据
			 */
			XmlHelp.createXml("B02"+"("+loanapplyNo+")",returnXml,"BOCB02RS", bocUtil.getEaFtpInfo());	
			Element rsRoot = XmlHelp.getRootByString(returnXml);
			Element head = rsRoot.getChild("HEADER");
			String trncod_rs = head.getChildText("RETCODE")==null?"":head.getChildText("RETCODE");
			if (!EAContant.BOC001RS.equals(trncod_rs.toLowerCase())) {
				throw new Exception(head.getChildText("NOTE"));
			}
			Document doc = DocumentHelper.parseText(returnXml);
			org.dom4j.Element node = doc.getRootElement();
			org.dom4j.Element body = node.element("BODY");
			org.dom4j.Element output = body.element("OUTPUT");
			bocB02Dao.saveInfo(loanapplyNo, output);
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_SUCCESS, null);
			logger.info("授信信息调查调用成功,loanapplyNo:[{}],id:[{}]", loanapplyNo, id);
		} catch (Exception e) {
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR, e.getMessage());
			logger.error("授信信息调查出现异常，loanapplyNo:[{}], id：[{}]，errMsg：[{}]", loanapplyNo, id, e);
			e.printStackTrace();
		} 
		return null;
	}
	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("B02");
		logEntity.setTypeName("授信信息调查");
		logEntity.setStartTime(new Date());
		return logEntity;
	}
}
